package com.kaviddiss.bootquartz.service;

import com.kaviddiss.bootquartz.bean.JobKeyModel;
import com.kaviddiss.bootquartz.config.Constants;
import com.kaviddiss.bootquartz.config.TimerUntils;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by Studio on 2017/5/20.
 */
@Service
public class JobService {
    @Autowired
    public Scheduler scheduler;
    @Autowired
    public JobKeyModel jobKeyModel;


    public boolean createJob(String className,String jobName,String triggerName,String date,String content)
            throws ClassNotFoundException, SchedulerException {


        String cron = TimerUntils.formatDateByPattern(TimerUntils.StrToDate(date),Constants.dateFormat);
        Class myclass;
        String myClassName;
        if(Constants.classMap.containsKey(className)){
            myClassName = Constants.classMap.get(className);
        }else{
            return false;
        }

        myclass = Class.forName(myClassName);
        JobDetail jobDetail = JobBuilder.newJob(myclass).withIdentity(jobName, Constants.JOB_GROUP).build();
        JobKey jobKey = jobDetail.getKey();
        jobDetail.getJobDataMap().put("Test",content);
        // 触发器
        TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
        // 触发器名,触发器组,触发器时间设定
        triggerBuilder.withIdentity(triggerName, Constants.TRIGGER_GROUP_NAME).startNow().withSchedule(CronScheduleBuilder.cronSchedule(cron));
        // 创建Trigger对象
        CronTrigger trigger = (CronTrigger) triggerBuilder.build();

        scheduler.scheduleJob(jobDetail, trigger);
        jobKeyModel.putJobKey(jobName,jobKey);
        return true;
    }

    public boolean deleteJob(String jobName)
            throws ClassNotFoundException, SchedulerException {

        JobKey jobKey = jobKeyModel.getJobKey(jobName);
        if(jobKey != null){
            scheduler.deleteJob(jobKey);
            jobKeyModel.deleteJobKey(jobName);
            return true;
        }
        return false;
    }

}
